package edu.hrbeu.crc.controller;


import edu.hrbeu.crc.constant.ErrorConstant;
import edu.hrbeu.crc.context.BaseContext;
import edu.hrbeu.crc.pojo.dto.UserDTO;
import edu.hrbeu.crc.pojo.dto.UserLoginDTO;
import edu.hrbeu.crc.pojo.entity.User;
import edu.hrbeu.crc.pojo.result.Result;
import edu.hrbeu.crc.pojo.vo.UserLoginVO;
import edu.hrbeu.crc.pojo.vo.UserVO;
import edu.hrbeu.crc.properties.JwtProperties;
import edu.hrbeu.crc.service.UserService;
import edu.hrbeu.crc.common.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        log.info("用户注册：{}", userDTO.toString());
        if (userDTO.getUsername() == null || userDTO.getUsername().isEmpty() || userDTO.getPassword() == null || userDTO.getPassword().isEmpty()) {
            return Result.error(ErrorConstant.NAME_NULL_OR_PASSWORD_NULL);
        }
        String regex = "^[A-Za-z\\d](?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d_]{6,18}$";
        if (!userDTO.getPassword().matches(regex)) {
            return Result.error(ErrorConstant.PASSWORD_VIOLATION);
        }
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        String message = userService.register(user);
        if (message == null) {
            return Result.success();
        } else {
            return Result.error(message);
        }
    }

    /**
     * 登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO.toString());
        User user = userService.login(userLoginDTO);
        if (user != null) {
            // 生成jwt令牌
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            String jwt = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claims);
            UserLoginVO userLoginVO = UserLoginVO.builder()
                    .id(user.getId())
                    .username(user.getUsername())
                    .token(jwt)
                    .build();
            return Result.success(userLoginVO);
        }else {
            return Result.error(ErrorConstant.LOGIN_ERROR);
        }
    }

    /**
     * 修改信息
     * @param userDTO
     * @return
     */
    @PutMapping("/update")
    public Result userMsgUpdate(@RequestBody UserDTO userDTO) {
        log.info("用户修改信息：{}，{}", userDTO.toString(), BaseContext.getCurrentId());

        String msg = userService.updateMsg(userDTO);
        if (msg == null) {
            return Result.success();
        } else {
            return Result.error(msg);
        }
    }

    @GetMapping("/get")
    public Result get() {
        Integer userId = BaseContext.getCurrentId();
        log.info("回显用户信息：{}",userId);
        // 得到解密后内容
        User user = userService.getUser(userId);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return Result.success(userVO);
    }
}
